import  logging

from LMS.settings import EMAIL_HOST_USER
from django.core.mail import send_mail
from celery_tasks.main import app
logger =logging.getLogger(__name__) # 用文件名命名日志器

@app.task(name = 'send_mail_task') #通过celery提交任务
def send_mail_task(email,username,password,classes_name):
    """
    发送通知邮件
    :param email:收件人邮箱
    :param username:用户名
    :param password:初始密码
    :param classes_name:所属班级名
    :return:
    """
    email_param = {
        'subject':'码趣教育——LMS学习系统',
        'message':'',
        'html_message':
            f"""
                <h2>欢迎加入码趣教育{classes_name}</h2>
                <p>您的登录用户名是：<span style='color:red'>[{username}]</span></p>
                <p>您的初始登录密码是：<span style='color:blue'>[{password}]</span>,请及时登录修改密码</p>
                <p><a href='http://127.0.0.1:8080'>点击访问码趣教育-LMS系统</a></p>
            """,
        'from_email':EMAIL_HOST_USER,# 发送邮件
        'recipient_list':[email], # 接收邮件
    }
    try:
        res_mail = send_mail(**email_param)
    except Exception as e:
        logger.error(f'邮件发送[异常][email:{email},message:{e}]')
    else:
        if res_mail != 1:
            logger.warning(f'邮件发送[失败][email:{email}]')
        else:
            logger.info(f'邮件发送[正常][email:{email},username:{username}]')

